<template>
  <div class="time-line">
    <div class="p-lr-12 mtb-20">
      <el-slider v-model="scaleValue" :min="10" :max="100" />
    </div>
    <div class="scale flex" :style="{ '--itemWidth': scaleValue ? scaleValue + 'px' : '10px' }">
      <div class="item" v-for="(item, index) in 301" :key="index">
        <div class="title">{{ index % 5 === 0 ? index : '' }}</div>
        <div :class="['line', index % 5 === 0 ? 'active': '']"></div>
      </div>
    </div>
    <div class="bottom m-tb-20">
      <div class="banner"></div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      scaleValue: 0
    }
  },
  methods: {
    init() {
      const banner = document.querySelector('.banner')
      const container = document.querySelector('.time-line')
      const containerRight = container.getBoundingClientRect().right
      // initPosX 初始的 banner 位置
      let initPosX = banner.offsetLeft, isDragging = false, mousedownX = 0
      document.addEventListener('mousemove', ({ x }) => {
        /*
        * 鼠标坐标 - banner的offsetLeft - 鼠标距离banner左侧的距离 = 最终需要移动的距离
        * 下面是在判断左右边界的情况
        * */
        if (isDragging && x >= initPosX + mousedownX && x + banner.offsetWidth - mousedownX < containerRight) banner.style.marginLeft = x - initPosX - mousedownX + 'px'
      })
      document.addEventListener('mouseup', () => { isDragging = false })
      banner.addEventListener('mousedown', ({ x }) => {
        mousedownX = x - banner.offsetLeft // 鼠标按下的位置距离在 banner 左侧的距离
        isDragging = true
      })
    }
  },
  mounted() {
    this.init()
  }
}
/*
* https://zhuanlan.zhihu.com/p/65082165
* */
</script>

<style scoped lang="scss">
.time-line {
  //overflow: hidden;
  border: 1px solid red;
  .scale {
    height: 50px;
    .item {
      display: flex;
      flex-shrink: 0;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
      width: var(--itemWidth);
      border-bottom: 1px solid cornflowerblue;
      user-select: none;
      .title {
        height: 30px;
      }
      .line {
        height: 10px;
        width: 1px;
        background-color: cornflowerblue;
        &.active {
          height: 20px;
        }
      }
    }
  }
  .bottom {
    .banner {
      width: 200px;
      height: 20px;
      background-color: cornflowerblue;
    }
  }
}
</style>